package cn.liye.pingfen.Util;

import cn.liye.pingfen.Util.WordFilteredRequest;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/*")
public class WordFilter implements Filter {

    // 敏感词汇列表，可以根据需求扩展
    private static final String[] SENSITIVE_WORDS = {"敏感词1", "敏感词2", "敏感词3"};

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 获取用户输入的文本
        String userInput = request.getParameter("content");

        // 检查是否包含敏感词汇
        for (String word : SENSITIVE_WORDS) {
            if (userInput.contains(word)) {
                // 替换敏感词汇为*
                userInput = userInput.replaceAll(word, "*");
            }
        }

        // 将处理后的文本传递给下一个过滤器或 Servlet
        chain.doFilter(new WordFilteredRequest((HttpServletRequest) request, userInput), response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 过滤器初始化操作，可留空
    }

    @Override
    public void destroy() {
        // 过滤器销毁操作，可留空
    }
}
